/*
 *  @ 属于哪个服务 urqNodeHttp = 1, borrowMoney = 2, http = 3, nodeHttp = 4, strategyHttp = 5, markeHttp = 6
 */
import axios from 'axios';
import QS from 'qs';
// import store from '../store';
import router from '../router';
import { Notify, Toast } from 'vant';
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_SERVER_URL, // 如果接口基地址是不一样，就取传过来的
  withCredentials: true
});
// request拦截器
service.interceptors.request.use(
  config => {
    config.headers['token'] = localStorage.getItem('Token') || '';
    if (config.url.indexOf('m/upload') === -1 || config.url.indexOf('m/upload/base64') === -1) {
      config.data = QS.stringify(config.data, { allowDots: true });
    }
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错strategyHttp
     */
    if (response.data.code === 1001) {
      Toast('登录超时,请重新登录');
      localStorage.removeItem('Token');
      router.push({ path: '/login' });
      // store.dispatch('setLogin', true);
      return;
    }
    if (!response.data.code) {
      return response.data;
    } else {
      // 判断产品下单时间的
      if (response.data.code !== 111) {
        response.data.message && Toast(response.data.message);
      }
      return response.data;
    }
  },
  error => {
    // console.log(error.response.data);
    if (error.response && error.response.status === 500) {
      Notify({
        message: '无法请求到服务器',
        type: 'danger'
      });
    } else if (error.response && error.response.status === 404) {
      Notify({
        message: '找不到-' + error.response.config.url + '-接口',
        type: 'danger'
      });
    } else {
      Notify({
        message:
          (error.response && (error.response.data.msg || (error.response && error.response.data.RMsg))) ||
          '无法请求到服务器',
        type: 'danger'
      });
    }
    return Promise.reject(error);
  }
);
export default {
  post: function(options) {
    var data = {
      url: options.url,
      method: 'post',
      data: options.params,
      timeout: options.timeout || 600000, // 请求超时时间
      onUploadProgress: options.onUploadProgress,
      headers: options.headers || {
        // 'Content-Type': 'application/json;charset=UTF-8'
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      }
    };
    return service(data);
  },
  get: function(options) {
    var data = {
      url: options.url,
      method: 'get',
      params: options.params,
      timeout: options.timeout || 600000, // 请求超时时间
      headers: options.headers || {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    };
    return service(data);
  }
};
